package com.tomicalab.mobiletoken.ckca;

import org.bouncycastle.util.encoders.Base64;

import iaik.pkcs.pkcs11.wrapper.PKCS11Exception;
import cfca.mobile.keydevice.AudioToken;
import com.ft.key.audio.comm.ACException;
import com.tomicalab.mobiletoken.ckca.utils.Constant;
import com.tomicalab.mobiletoken.ckca.utils.CustomProgressDialog;
import com.tomicalab.mobiletoken.ckca.utils.P11Other;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TabActivity;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
public class CKCA extends TabActivity {
	private Context context;
	private Resources res;
	private TabHost tabhost;
	
	private BroadcastReceiver headSetReceiver = null;
	private static CustomProgressDialog progressDialog;
	private static handler handler;
	
	private static boolean isConnected = false;
	public  static boolean isLogin = false;
	boolean btryConnect = false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_ckc);
		
		context = this;
		res = this.getResources();
		
		tabhost = getTabHost();
		
		Intent intent;
		TabHost.TabSpec spec;
		
		intent = new Intent().setClass(this, ChangePIN.class);
		spec = tabhost.newTabSpec("changepin")
				.setIndicator(gettabview(tabhost.getContext(),res.getDrawable(R.drawable.keys), res.getString(R.string.tabname_changepin)))
				.setContent(intent);
		
		tabhost.addTab(spec);
		
		intent = new Intent().setClass(this, UnBlockPIN.class);
		spec = tabhost.newTabSpec("unblockpin")
				.setIndicator(gettabview(tabhost.getContext(),res.getDrawable(R.drawable.lock_icon), res.getString(R.string.tabname_unblockpin)))
				.setContent(intent);
		
		tabhost.addTab(spec);
		
		intent = new Intent().setClass(this, Certificate.class);
		spec = tabhost.newTabSpec("certificate")
				.setIndicator(gettabview(tabhost.getContext(),res.getDrawable(R.drawable.cert), res.getString(R.string.tabname_certificate)))
				.setContent(intent);
		
		tabhost.addTab(spec);
		
		intent = new Intent().setClass(this, RenewCert.class);
		spec = tabhost.newTabSpec("renew")
				.setIndicator(gettabview(tabhost.getContext(),res.getDrawable(R.drawable.renew), res.getString(R.string.tabname_renew)))
				.setContent(intent);
		
		tabhost.addTab(spec);
		
		handler = new handler();
		progressDialog = new CustomProgressDialog(this);
		progressDialog.setCancelable(false);
		
        headSetReceiver = new BroadcastReceiver() {
        	public void onReceive(Context context, Intent intent) {
        		String action = intent.getAction();
        		if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
        			if(intent.getIntExtra("state", 0) == 1){
        				Log.d(Constant.Debug, "Handset plugin");
        				P11Other.isTokenPlugned = 1;
        				tryConnect();
        				/*
						if(P11Other.isLoadlib == 1)
						{
							progressDialog.setShowInfo(res.getString(R.string.inform_tryconnect_init));
							handler.sleep(0, Constant.SHOWPROGRESSDIALOG, "");
							new Thread() {
								public void run() {
									try {
										P11Other.getTokenInfo();
									} catch (PKCS11Exception e) {
										e.printStackTrace();
									}
									handler.sleep(0, Constant.CLOSEPROGRESSDIALOG, "");
								}
							}.start();
							
						} else {
								
						}
						*/
        			}else{
        				Log.d(Constant.Debug, "Handset plugout");
        				if (isConnected)
        		    	{
        		    		isConnected = false;
        		    	}
        				P11Other.isTokenPlugned = 0;
        				disConnect();
        			}
        		}
        	}
        };
        registerReceiver(headSetReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
		
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch(id)
		{
		case 0:
			return new AlertDialog.Builder(context)
			.setTitle(res.getString(R.string.inform_title))
			.setCancelable(false)
			.setMessage(res.getString(R.string.inform_handset_plugout))
	        .create();
		}
		return super.onCreateDialog(id);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.e(Constant.Debug, "onDestroy ckca");
		disConnect();
		unregisterReceiver(headSetReceiver);
	}
	private View gettabview(Context context,Drawable id_icon,CharSequence charSequence)    
    {
    	LayoutInflater li=LayoutInflater.from(context);    	
    	View view = li.inflate(R.layout.tab_item, null);    	
    	ImageView item=(ImageView)view.findViewById(R.id.tab_image);
    	TextView tv_item = (TextView)view.findViewById(R.id.tab_text);    	
    	item.setBackgroundDrawable(id_icon);
    	tv_item.setText(charSequence);
    	return view;
    	
    }
    
    private void tryConnect()
    {
		progressDialog.setShowInfo(res.getString(R.string.inform_tryconnect_init));
    	handler.sleep(0, Constant.SHOWPROGRESSDIALOG, "");
    	new Thread() {
    		public void run()
    		{
    			btryConnect = false;
    			try {
    				if (!P11Other.p11initialize(getApplicationContext())) {
    					P11Other.p11finalize();
    					isConnected = false;
    				} else {
    					isConnected = true;
    					Log.e(Constant.Debug, "Connected");
    				}
    				
    				if (isConnected)
    				{
    					P11Other.getSlotInfo();
	    				P11Other.getTokenInfo();
	    				P11Other.openSession();
	    				Log.e(Constant.Debug, "Get Info OK");
    				}
    			} catch (PKCS11Exception e) {
					e.printStackTrace();
					isConnected = false;
				} catch (Exception e) {
					e.printStackTrace();
					isConnected = false;
				}
    			handler.sleep(0, Constant.CLOSEPROGRESSDIALOG, "");
    			if (isConnected)
    			{
    				//do nothing
    			}
    			else
    			{
    				String msg;
    				msg = res.getString(R.string.inform_handset_connectfail);
    				handler.sleep(100, Constant.SHOWERRINFO, msg);
    			}
    			btryConnect = true;
    		}
    	}.start();	
    	
    }
    
	private void disConnect()
    {
		try {
			if(isLogin)
			{
				P11Other.logout();
			}
			isLogin = false;
			
		} catch (PKCS11Exception e) {
			e.printStackTrace();
		}

    	P11Other.p11finalize();
    }
    
	public class handler extends Handler {
		String oldPassword, newPassword;
		public void sleep(long delayMillis, int msgID, Object obj) {
            this.removeMessages(msgID);
            Message msg = new Message();
            msg.what = msgID;
            msg.obj  = obj;
            sendMessageDelayed(msg, delayMillis);
        }
		
		public void sleep(long delayMillis, int msgID, String oldPassword, String newPassword) {
            this.removeMessages(msgID);
            Message msg = new Message();
            msg.what = msgID;
            msg.obj  = oldPassword;
            sendMessageDelayed(msg, delayMillis);
            this.oldPassword = oldPassword;
            this.newPassword = newPassword;
        }
		
		public void handleMessage(Message msg) {
			switch(msg.what) {
			case Constant.SHOWPROGRESSDIALOG:
				Log.e(Constant.Debug, "SHOWPROGRESSDIALOG");
				progressDialog.show();
				super.handleMessage(msg);
				break;
			case Constant.CLOSEPROGRESSDIALOG:
				progressDialog.dismiss();
				super.handleMessage(msg);
				break;
			case Constant.SHOWERRINFO:
				if (null != msg.obj)
				{
					if(msg.obj.toString().compareTo(res.getString(R.string.inform_handset_connectfail))==0)
					{
						String title, button;
			    		button = res.getString(R.string.inform_button_OK);
						title = res.getString(R.string.inform_title);
						new Builder(context)
				    	.setTitle(title)
				    	.setMessage(msg.obj.toString())
				    	.setPositiveButton(button, new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								finish();
							}
						}).show();
					}
					else
						Constant.showMessage(msg.obj.toString(), context, res);
				}
				super.handleMessage(msg);
				break;
			}			
		}
	}
}
